<template>
  <!-- 新建列表 -->
  <div class="activitybox">
    <el-card class="search-box">
      <div class="ipt_box">
        <div class="leftbox" style="flex: 90%">
          <div>
            <span>活动搜索：</span>
            <el-input
              v-model="input"
              placeholder="请输入要查询的姓名"
              clearable
              style="width: 70%"
            />
          </div>
          <div class="selectbox">
            <el-cascader
              ref="cascader"
              v-model="devalue"
              :show-all-levels="false"
              style="width: 200px"
              :options="departlist"
              :props="postProps"
              clearable
              filterable
              placeholder="请搜索选择部门"
            />
          </div>
          <div class="selectbox">
            <el-select v-model="nodeName" placeholder="请选择考核状态" clearable>
              <el-option
                v-for="item in nodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="selectbox">
            <el-cascader
              v-model="postvalue"
              :show-all-levels="false"
              style="width: 200px"
              :options="postlist"
              :props="postProps"
              clearable
              filterable
              placeholder="请搜索选择岗位"
            />
          </div>
          <div class="selectbox">
            <searchSelect
              v-model="flowId"
              placeholder="请搜索选择考核类型"
              :loading="templateSelect.loading"
              :options="templateSelect.options"
              :filterable="true"
              :total-pages="templateSelect.total"
              :current.sync="templateSelect.current"
              :size.sync="templateSelect.size"
              @getOption="getTypeOptions"
            />
          </div>
          <el-button
            style="margin-left: 2%"
            type="primary"
            icon="el-icon-search"
            @click="listseach"
          >搜索</el-button>
          <el-button
            style="margin-left: 2%"
            type="primary"
            @click="restseach"
          >重置</el-button>
        </div>
        <div class="rightbox" style="flex: 10%">
          <el-popover
            placement="bottom"
            width="100"
            trigger="hover"
            popper-class="message-popover"
          >
            <div class="exportList">
              <div
                v-for="(item, index) in exportList"
                :key="index"
                class="exportList_item"
                style="text-align: center;margin-bottom: 10px;"
                @click="exportItem(item.event)"
              >
                <div v-if="item.name!='车间绩效考核总表'||item.name==='车间绩效考核总表' && UserName ==='admin'">{{ item.name }}</div>
              </div>
            </div>
            <el-button
              slot="reference"
              icon="el-icon-upload2"
              size="medium"
              type="primary"
            >导出</el-button>
          </el-popover>
        </div>
      </div>
    </el-card>

    <el-card class="list-box">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="time" label="发起时间" />
        <el-table-column prop="initiator" label="考核发起人" />
        <el-table-column prop="nickName" label="被考核人姓名" />
        <el-table-column prop="departmentTitle" label="部门" />
        <el-table-column prop="postTitle" label="岗位" />
        <el-table-column prop="flowTemplateName" label="考核类型" />
        <el-table-column prop="score" label="考核结果" />
        <el-table-column prop="" label="考核状态">
          <template slot-scope="scope">
            <span
              v-if="scope.row.nodeName === '考核结束'"
              style="color: #5cb85c"
            >{{ scope.row.nodeName }}</span>
            <span v-else style="color: #428bca">{{ scope.row.nodeName }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="elapsedTime" label="审核累计用时">
          <template slot-scope="scope">
            <div
              :style="{
                color: setColor(
                  scope.row.assessmentStatus,
                  scope.row.elapsedTimeStatus
                )
              }"
            >
              {{ scope.row.elapsedTime }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="操作">
          <template slot-scope="scope">
            <!-- @click="changefrom(scope.row, scope.$index)" -->
            <el-button
              size="mini"
              type="primary"
              round
              @click="goxiangq(scope.row, scope.$index)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 明细导出 -->
    <el-dialog title="绩效考核明细表导出" :visible.sync="detailedShow">
      <el-form
        ref="detailedForm"
        :model="detailedForm"
        :rules="detailedRules"
        label-width="100px"
      >
        <el-form-item
          label="考核类型"
          :label-width="formLabelWidth"
          prop="assessmentType"
        >
          <searchSelect
            v-model="detailedForm.assessmentType"
            placeholder="请搜索选择考核类型"
            :loading="templateSelect.loading"
            :options="templateSelect.options"
            :filterable="true"
            :total-pages="templateSelect.total"
            :current.sync="templateSelect.current"
            :size.sync="templateSelect.size"
            style="width: 300px"
            @getOption="getTypeOptions"
          />
        </el-form-item>
        <el-form-item
          label="选择部门"
          :label-width="formLabelWidth"
          prop="department"
        >
          <el-cascader
            ref="cascader"
            v-model="detailedForm.department"
            :show-all-levels="false"
            style="width: 300px"
            :options="departlist"
            :props="props"
            clearable
            filterable
            placeholder="请搜索选择部门"
          />
        </el-form-item>

        <el-form-item
          label="时间范围"
          :label-width="formLabelWidth"
          prop="timeFrame"
        >
          <el-date-picker
            v-model="detailedForm.timeFrame"
            style="width: 300px"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailedInso('detailedForm')">取 消</el-button>
        <el-button
          type="primary"
          @click="detailedInok('detailedForm')"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 总表导出 -->
    <el-dialog title="车间考核总表导出" :visible.sync="summaryShow">
      <el-form
        ref="summaryForm"
        :model="summaryForm"
        :rules="summaryRules"
        label-width="100px"
      >
        <el-form-item
          label="时间范围"
          :label-width="formLabelWidth"
          prop="timeFrame"
        >
          <el-date-picker
            v-model="summaryForm.timeFrame"
            style="width: 300px"
            type="month"
            value-format="yyyy-MM"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="summaryIsno('summaryForm')">取 消</el-button>
        <el-button
          type="primary"
          @click="summaryIsok('summaryForm')"
        >确 定</el-button>
      </div>
    </el-dialog>

    <div style="margin-left: 50%; margin-top: 10px">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalcount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import searchSelect from '@/components/SearchSelect'
export default {
  components: {
    searchSelect
  },
  data () {
    return {
      input: '',
      currentPage: 1,
      pageSize: 10,
      totalcount: 0,
      tableData: [],
      flowId: '', // 考核类型
      departlist: [], // 部门
      postlist: [], // 岗位
      devalue: '', // 部门
      postvalue: '', // 岗位
      nodeName: '', // 考核状态
      nodeOptions: [{
          value: 1,
          label: '其它'
        }, {
          value: 2,
          label: '考核结束'
      }],
      postProps: { multiple: false, emitPath: false, checkStrictly: true },
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      exportList: [
        {
          name: '绩效考核明细表',
          value: '0',
          event: 'detailed'
        },
        {
          name: '车间绩效考核总表',
          value: '1',
          event: 'summary'
        }
      ],
      detailedShow: false, // 明细弹窗show
      summaryShow: false, // 总表弹窗show
      // 明细
      detailedForm: {
        assessmentType: '', // 考核类型
        department: [], // 部门
        timeFrame: ''
      },
      templateSelect: {
        options: [],
        loading: false,
        total: 0,
        current: 1,
        size: 50
      },
      detailedRules: {
        assessmentType: [
          { required: true, message: '请选择考核类型', trigger: 'change' }
        ],
        timeFrame: [
          { required: true, message: '请选择时间范围', trigger: 'change' }
        ],
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ]
      },
      props: { multiple: true, emitPath: false },
      departmentOptions: [], // 部门
      // 总表
      summaryForm: {
        timeFrame: '' // 时间范围
      },
      summaryRules: {
        timeFrame: [
          { required: true, message: '请选择时间范围', trigger: 'change' }
        ]
      },
      formLabelWidth: '100px'
    }
  },
  computed: {
    UserName() {
      return this.$store.state.user.name
    },
    setColor () {
      // elapsedTimeStatus  0未超时 1已超时
      // assessmentStatus 1 未完成   2 已完成
      return function (assessmentStatus, elapsedTimeStatus) {
        if (elapsedTimeStatus === '1' && assessmentStatus === '2') {
          // 已超时 已完成
          return '#FF0000'
        } else if (elapsedTimeStatus === '1' && assessmentStatus !== '2') {
          // 已超时 未完成
          return '#000'
        } else if (elapsedTimeStatus === '0' && assessmentStatus === '2') {
          // 未超时 已完成
          return 'rgb(92, 184, 92)'
        } else if (elapsedTimeStatus === '0' && assessmentStatus !== '2') {
          // 未超时 未完成
          return '#A9A9A9'
        }
      }
    }
  },
  watch: {
    devalue (newval, oldval) {
      if (newval) {
        this.getPostList(newval)
      }
    }
  },
  created () {
    this.getlist()
    this.getDepartmentList() // 部门
    this.getPostList('')
  },
  methods: {
    // 重置
    restseach () {
      this.input = ''
      this.devalue = ''
      this.postvalue = ''
      this.flowId = ''
      this.nodeName = ''
      this.getPostList('')
    },
    // 获取岗位
    async getPostList (departId) {
      try {
        const res = await this.$Http.getPostList({ departId: departId })
        if (res.code === 200) {
          this.postlist = res.result
        } else {
          this.$message({
            type: 'error',
            message: res.messsage
          })
          this.postlist = []
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 递归
    recursion (item) {
      if (item.childrenDepartment != null) {
        item.children = item.childrenDepartment
        if (item.children.length > 0) {
          item.value = item.id
          item.label = item.title
          item.children.forEach(ff => {
            this.recursion(ff)
          })
        } else {
          item.value = item.id
          item.label = item.title
          item.children = []
        }
      } else {
        item.value = item.id
        item.label = item.title
        item.childrenDepartment = []
      }
    },
    // 获取部门树
    async getDepartmentList () {
      try {
        const res = await this.$Http.getdDepartment()

        if (res.code === 200) {
          this.departlist = res.result
          this.departlist.forEach(item => {
            this.recursion(item)
          })
        } else {
          this.$message({
            type: 'error',
            message: res.messsage
          })
          this.departlist = []
        }
      } catch (error) {
        console.log('error0', error)
      }
    },
    initSelectOption () {
      this.templateSelect.current = 1
      this.getTypeOptions({
        pageInfo: {
          current: this.templateSelect.current,
          size: this.templateSelect.size
        }
      })
    },
    // 获取考核类型
    getTypeOptions (data) {
      const { pageInfo, searchValue } = data
      const params = Object.assign({}, pageInfo)
      if (searchValue) params.actTypeName = searchValue
      this.templateSelect.loading = true
      this.$Http
        .getActivityType(params)
        .then(response => {
          this.templateSelect.loading = false
          const { result } = response
          this.templateSelect.total = result.totalRows
          if (Array.isArray(result.resultData)) {
            this.templateSelect.options = result.resultData.map(info => {
              return {
                value: info.id,
                label: info.actTypeName,
                id: info.id
              }
            })
          }
        })
        .catch(error => {
          this.templateSelect.loading = false
          console.log(error)
        })
    },
    // 明细取消
    detailedInso (formName) {
      this.$refs[formName].resetFields()
      this.detailedShow = false
    },
    downloadURL (url, count) {
      var hiddenIFrameID = 'hiddenDownloader' + count++
      var iframe = document.createElement('iframe')
      iframe.id = hiddenIFrameID
      iframe.style.display = 'none'
      document.body.appendChild(iframe)
      iframe.src = url // 直接下载，不会弹出新的页面
    },
    // 明细确定
    // detailedInok (formName) {
    //   this.$refs[formName].validate(valid => {
    //     if (valid) {
    //       // this.detailedForm.department.forEach((item) => {
    //       //   console.log('啊', item)
    //       // })

    //       var urlList = []
    //       var count = 0
    //       for (var i = 0; i < this.detailedForm.department.length; i++) {
    //         urlList.push(
    //           `${process.env.VUE_APP_BEG_IP}xboot/report/getHkAssessmentScoreGroupByUser?departmentId=${this.detailedForm.department[i]}&beginDate=${this.detailedForm.timeFrame[0]}&endDate=${this.detailedForm.timeFrame[1]}&flowTemplateId=${this.detailedForm.assessmentType}`
    //         )
    //       }
    //       for (var c = 0; c < urlList.length; c++) {
    //         this.downloadURL(urlList[c], count)
    //       }
    //       setTimeout(() => {
    //         this.detailedShow = false
    //       }, 2000)
    //     } else {
    //       console.log('error submit!!')
    //       return false
    //     }
    //   })
    // },
    detailedInok (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
            window.location.href = `${process.env.VUE_APP_BEG_IP}xboot/report/getHkAssessmentScoreGroupByUser?departmentId=${this.detailedForm.department.join(',')}&beginDate=${this.detailedForm.timeFrame[0]}&endDate=${this.detailedForm.timeFrame[1]}&flowTemplateId=${this.detailedForm.assessmentType}`
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 总表取消
    summaryIsno (formName) {
      this.$refs[formName].resetFields()
      this.summaryShow = false
    },
    // 总表确定
    summaryIsok (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          window.location.href = `${process.env.VUE_APP_BEG_IP}xboot/Chart/createChartSetDataTo?monthDate=${this.summaryForm.timeFrame}`
          setTimeout(() => {
            this.summaryShow = false
          }, 2000)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  导出弹窗
    exportItem (event) {
      if (event === 'detailed') {
        this.detailedShow = true
      } else if (event === 'summary') {
        this.summaryShow = true
      }
    },
    // 去详情
    goxiangq (row, index) {
      this.$router.push({
        path: '/form/activityxiangqing',
        query: {
          processInstanceId: row.processInstanceId,
          departmentTitle: row.departmentTitle,
          nickName: row.nickName,
          postTitle: row.postTitle,
          time: row.time,
          score: row.score,
          nodeName: row.nodeName,
          initiator: row.initiator
        }
      })
    },

    // 开始时间
    beginDate () {
      return {
        disabledDate (time) {
          return time.getTime() > Date.now() - 8.64e7 // 开始时间不选时，结束时间最大值小于等于当天
        }
      }
    },
    // 提出结束时间必须大于提出开始时间
    processDate () {
      const self = this
      return {
        disabledDate (time) {
          if (self.ruleForm.StartAt) {
            return new Date(self.ruleForm.StartAt).getTime() > time.getTime()
          } else {
            return time.getTime() < Date.now() - 8.64e7 // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      }
    },

    // 搜索
    listseach () {
      this.tableData = []
      this.getlist()
    },
    // 列表
    async getlist () {
      try {
        const res = await this.$Http.activitylistquery({
          pageNumber: this.currentPage,
          pageSize: this.pageSize,
          nickName: this.input,
          departmentId: this.devalue,
          postId: this.postvalue,
          nodeName: this.nodeName,
          flowTemplateId: this.flowId
        })
        if (res.code === 200) {
          this.tableData = res.result.resultData
          this.totalcount = res.result.totalRows
        } else {
          this.tableData = []
          this.totalcount = 0
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      } catch (err) {
        console.log('err', err)
      }
    },
    // 分页
    handleSizeChange (val) {
      this.pageSize = val
      this.getlist()
    },
    handleCurrentChange (val) {
      this.currentPage = val

      this.getlist()
    }
  }
}
</script>
<style lang="scss">
.el-popper[x-placement^='bottom'] {
  margin-top: 0 !important;
}
.message-popover {
  padding: 0 !important;
  background-color: #9ccaff;
}

.exportList {
  &_item {
    font-size: 12px;
    margin-top: 10px;
    text-align: center;
    color: #000;
  }
  &_item:hover {
    color: #1a70ff !important;
  }
}
</style>

<style lang="less" scoped="scoped">
.activitybox {
  padding: 10px 10px 0 10px;
  box-sizing: border-box;
  .search-box {
    .ipt_box {
      display: flex;
      justify-content: space-between;
      align-items: cneter;
      margin-bottom: 50px;
      .leftbox {
        display: flex;
        flex-wrap: wrap;
        .selectbox {
          margin-bottom: 10px;
          margin-left: 20px;
        }
      }
      .rightbox {
      }
    }
  }
  .list-box {
    margin-top: 10px;
  }
}
</style>
